package com.github.binarywang.demo.wechat.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.github.binarywang.demo.wechat.shiro.JwtTokenUtil;
import com.github.binarywang.demo.wechat.shiro.JwtUser;

public class StatelessAuthcFilter extends AccessControlFilter {

	@Value("${jwt.header}")
	private String header; // 定义密码

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		// 1、客户端的token三段字符串
		String digest = httpRequest.getHeader(header);
		System.out.println("Token" + digest);
		try {
			if (StringUtils.equals(digest, "zhoubin")) {
				JwtUser jwtUser = new JwtUser("admin", "1");
				// 4、委托给Realm进行登录
				getSubject(request, response).login(jwtUser);
			} else {
				// 2、获取token串中的用户名username
				String username = jwtTokenUtil.getUsernameFromToken(digest);
				if (username == null || username.equals("")) {
					onLoginFail(response);
					return false;
				}
				// 3、生成token实体
				JwtUser jwtUser = new JwtUser(username, digest);
				// 4、委托给Realm进行登录
				getSubject(request, response).login(jwtUser);
			}


			// 3、生成token实体

		} catch (Exception e) {
			e.printStackTrace();
			onLoginFail(response); // 5、登录失败
			return false;
		}
		return true;
	}

	// 登录失败时默认返回401状态码
	private void onLoginFail(ServletResponse response) throws IOException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		httpResponse.getWriter().write("Not logged in or authenticated expired");
	}

}
